import { _decorator, Collider2D, color, Component, Contact2DType, find, instantiate, IPhysics2DContact, Node, Prefab, Sprite } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Brick')
export class Brick extends Component {
    @property(Prefab)
    prop_1:Prefab = null

    @property(Prefab)
    prop_2:Prefab = null

    @property(Prefab)
    prop_3:Prefab = null

    @property(Number)
    life:number = 1

    private sprite:Sprite


    start() {
        this.sprite = this.node.getComponent(Sprite)
        let collider = this.getComponent(Collider2D);
        collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }

    onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
    }

    die(){
        this.life--
    }

    prop(){
        let num = Math.random()*10
        if(num <= 1){
            let prop = instantiate(this.prop_1)
            find('Canvas/Props').addChild(prop)
            prop.setPosition(this.node.position)
        }else if(1< num && num<=2){
            let prop = instantiate(this.prop_2)
            find('Canvas/Props').addChild(prop)
            prop.setPosition(this.node.position)
        }
        else if(2< num && num<2.5){
            let prop = instantiate(this.prop_3)
            find('Canvas/Props').addChild(prop)
            prop.setPosition(this.node.position)
        }
    }

    update(deltaTime: number) {
        if(this.life <= 0){
            this.node.destroy()
            this.prop()
        }else if(this.life == 1){
            this.sprite.color = color(0,255,0,255)
        }else if(this.life == 2){
            this.sprite.color = color(0,0,255,255)
        }else if(this.life == 3){
            this.sprite.color = color(255,0,0,255)
        }
    }
}


